package com.example.myjson.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.example.myjson.model.Student;

import java.util.ArrayList;
import java.util.List;

public class StudentServiceImpl {

    /**
     * 入口程序
     * @param args
     */
    public static void main(String[] args) {
        Student stu1 = new Student(1,"小明",18,"南宁市西乡塘区");
        /**
         * java对象转json字符串
         */
        String jsonStr = example1(stu1);
        System.out.println("json字符串--:" + jsonStr);

        /**
         * json字符串转java对象
         */
        Student stu2 = example2(jsonStr);
        System.out.println("学生对象--："+stu2.toString());

        /**
         * java数组转json数组字符串
         */
        List<Student> list = new ArrayList<>();
        list.add(stu1);
        list.add(new Student(2,"小红",19,"南宁市良庆区"));
        list.add(new Student(3,"小黑",20,"南宁市江南区"));
        String json = example3(list);
        System.out.println("json数组字符串--:"+ json);

        /**
         * json数组字符串转java数组
         */
        List<Student> arr = example4(json);
        System.out.println("学生数组--："+arr.toString());

    }

    /**
     * java对象转json字符串
     */
    public static String example1(Student student){
        String str = JSON.toJSONString(student);
        return str;
    }

    /**
     * json字符串转java对象
     */
    public static Student example2(String jsonStr){
        Student student = JSON.parseObject(jsonStr,Student.class);
        return student;
    }

    /**
     * java数组转json数组字符串
     */
    public static String example3(List<Student> list){
        String str = JSON.toJSONString(list);
        return str;
    }

    /**
     * json数组字符串转java数组
     */
    public static List<Student> example4(String json){
        List<Student> list = new ArrayList<>();
        list = JSONArray.parseArray(json,Student.class);
        return list;
    }


}
